package com.bee.beemanage.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bee.beemanage.api.entity.SysDepartment;
import com.bee.beemanage.api.entity.SysUser;
import com.bee.beemanage.api.entity.output.DepartmentTree;
import com.bee.beemanage.api.mapper.SysDepartmentMapper;
import com.bee.beemanage.api.mapper.SysUserMapper;
import com.bee.beemanage.api.service.SysDepartmentService;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author 陈国松
 * @since 2022-10-09
 */
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements SysDepartmentService {

    @Resource
    SysDepartmentMapper sysDepartmentMapper;

    @Resource
    SysUserMapper sysUserMapper;
    /**
     * 根据部门id构建部门树，部门id为null，则返回所有的部门树
     *
     * @param departmentId 部门id
     * @return 部门树
     */
    @Override
    public List<DepartmentTree> selectDepartmentTreeByDepartmentId(String departmentId) {
        List<SysDepartment> sysDepartments = new ArrayList<>();
        //查询所有部门信息
        sysDepartments =sysDepartmentMapper.selectList(null);
        List<DepartmentTree> ResultTree = new ArrayList<>();
        List<SysDepartment> RootDepartments;
        if(null==departmentId){
            //没有传根部门，则把没有上级部门的部门作为根部门
            RootDepartments = sysDepartments.stream().filter(sysDepartment -> null==sysDepartment.getPid())
                    .collect(Collectors.toList());
        }else{
            //有部门id，则以传入的部门id的部门作为根部门
            RootDepartments = sysDepartments.stream().filter(sysDepartment -> sysDepartment.getId()
                    .equals(departmentId)).collect(Collectors.toList());
        }
        for (SysDepartment rootDepartment : RootDepartments) {
            //构建成部门树的结构
            DepartmentTree departmentTree = new DepartmentTree();
            BeanUtils.copyProperties(rootDepartment,departmentTree);
            ResultTree.add(departmentTree);
        }
        getChildren(sysDepartments,ResultTree);
        return ResultTree;
    }

    /**
     * 递归构建部门树
     */
    public void getChildren(List<SysDepartment> SysDepartments, List<DepartmentTree> DepartmentTrees){
        //遍历根节点
        for (DepartmentTree departmentTree : DepartmentTrees) {
            List<SysDepartment> Childrens = SysDepartments.stream().filter(sysDepartment ->
                            (sysDepartment.getPid()!=null&&sysDepartment.getPid().equals(departmentTree.getId())))
                    .collect(Collectors.toList());
            if(Childrens.size()!=0){
                List<DepartmentTree> TmpTreeList = new ArrayList<DepartmentTree>();
                for (SysDepartment children : Childrens) {
                    DepartmentTree TmpTree = new DepartmentTree();
                    BeanUtils.copyProperties(children, TmpTree);
                    TmpTreeList.add(TmpTree);
                }
                departmentTree.setChildren(TmpTreeList);
                getChildren(SysDepartments,TmpTreeList);
            }
        }
    }

    @Override
    public Page<SysDepartment> recycleSearch(Page<SysDepartment> page, SysDepartment sysDepartment, LocalDateTime startTime, LocalDateTime endTime) {
        return sysDepartmentMapper.recycleSearch(page,sysDepartment,startTime,endTime);
    }

    @Override
    public boolean recover(List<String> idsList) {
        return sysDepartmentMapper.recover(idsList);
    }

    @Override
    public Result clear() {
        Result result = ResultTool.success();
        sysDepartmentMapper.clear();
        return result;
    }

    @Override
    public Result safeDeleteById(String id) {
        Result result = ResultTool.success();
        //判断是否有用户使用到了此部门
        QueryWrapper<SysUser> query = Wrappers.query();
        query.eq("is_deleted", "0")
                .eq("department_id", id);
        List<SysUser> sysUsers = sysUserMapper.selectList(query);
        if (null != sysUsers && sysUsers.size() > 0) {
            result = ResultTool.fail(ResultCode.IN_USING);
            result.setErrorMsg("部门被使用,无法删除");
            return result;
        }
        sysDepartmentMapper.selectById(id);
        return result;
    }
}
